package diet

import (
	"github.com/bgmp/config"
	"github.com/bgmp/middleware"
	"github.com/bgmp/model"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func (b Base) Report(c *gin.Context, req *ReportRequest) *ReportResponse {
	req.EndTime.Time = time.Date(req.EndTime.Time.Year(), req.EndTime.Month(), req.EndTime.Day(), 23, 59, 59, 0, req.EndTime.Time.Location())
	response := ReportResponse{}

	delta := -24 * time.Hour

	condition := model.DietSelectConditions{
		Start: model.Time{Time: req.EndTime.Time.Add(delta)},
		End:   model.Time{Time: req.EndTime.Time},
	}

	for i := 1; i <= 7; i++ {
		var dayReport DayReport
		diets := model.ListDietViews(config.DB,
			map[string]any{model.Diet_UserId: middleware.GetUserId(c)},
			&condition,
		)

		for _, diet := range diets {
			if diet.Type == "breakfast" {
				dayReport.Breakfast++
			} else if diet.Type == "lunch" {
				dayReport.Lunch++
			} else if diet.Type == "dinner" {
				dayReport.Dinner++
			} else if diet.Type == "snack" {
				dayReport.Snack++
			}
			for _, food := range diet.Foods {
				for _, nutrition := range food.Nutrition {
					s := nutrition.Value[:len(nutrition.Value)-1]
					f, err := strconv.ParseFloat(s, 64)
					if err != nil {
						continue
					}
					if nutrition.Key == "蛋白质" {
						dayReport.Protein += f
					} else if nutrition.Key == "脂肪" {
						dayReport.Fat += f
					} else if nutrition.Key == "碳水化合物" {
						dayReport.Cbd += f
					}
				}
			}
		}

		//fmt.Println(fmt.Sprintf("%s %s", condition.Start.Time, condition.End.Time), diets)

		// 减少1天
		condition.Start.Time = condition.Start.Time.Add(delta)
		condition.End.Time = condition.End.Add(delta)

		response.Diets = append(response.Diets, dayReport)
	}

	return &response
}

type ReportRequest struct {
	EndTime model.Time `json:"end_time"`
}

type DayReport struct {
	Breakfast int     `json:"breakfast"`
	Lunch     int     `json:"lunch"`
	Dinner    int     `json:"dinner"`
	Snack     int     `json:"snack"`
	Protein   float64 `json:"protein"`
	Cbd       float64 `json:"cbd"`
	Fat       float64 `json:"fat"`
}

type ReportResponse struct {
	Diets []DayReport `json:"diets"`
}
